# *-* coding: utf-8 *-*
# Crazy Minecraft Builder
# by SNWCreations
# Python 3 Powered

# Libraries

import json
import os
import re
import sys
import time
import shutil
from zipfile import ZipFile

from prettytable import PrettyTable
from windlib import (compress, extract,
                     find_files_with_the_specified_extension, pushd)

active = set()

# Functions


def manifest_data() -> dict:
    global active
    datadict = {}
    flist = find_files_with_the_specified_extension('zip', './packs')
    for x in flist:
        active.add(x)
        os.makedirs('./temp', exist_ok=True)
        with pushd('./temp'):
            z = ZipFile(x)
            z.extract('manifest.json')
            z.close()
            with open('./manifest.json', encoding='utf-8') as f:
                datadict[x] = json.load(f)
            os.remove('manifest.json')
        os.rmdir('./temp')
    return datadict


def show_info(datadict: dict):
    table = PrettyTable(['文件名', '模块名', '版本号', '作者', '是否启用'])
    for x in datadict:
        d = datadict[x]
        ver = str(d['version']).replace(
            '[', '').replace(', ', '.').replace(']', '')
        if not x in active:
            table.add_row(
                [os.path.basename(x), d['name'], ver, d['author'], '否'])
        else:
            table.add_row(
                [os.path.basename(x), d['name'], ver, d['author'], '是'])
    print(table)


def build(datadict: dict, filename: str) -> str:
    # Prepare Environment
    print('* 解压数据包基本结构 ... ', end='')
    extract('./blank_pack.zip', 'build')
    print('OK')
    lm = open('./build/data/cmc/functions/load.mcfunction',
              mode='a', encoding='utf-8')
    tm = open('./build/data/cmc/functions/tick.mcfunction',
              mode='a', encoding='utf-8')
    print('* 解压组件 ...')
    for x in datadict:
        if not x in active:
            continue
        print('     * 应用组件包', datadict[x]['name'], '... ', end='')
        extract(x, './build')
        with open('./build/manifest.json', encoding='utf-8') as f:
            d = json.load(f)
        if not d['loadfile'] == None:
            lm.write('function ' + d['loadfile'])
            lm.write('\n')
        if not d['tickfile'] == None:
            tm.write('function ' + d['tickfile'])
            tm.write('\n')
        # Delete manifest.json
        os.remove('./build/manifest.json')
        print('OK')
    lm.close()
    tm.close()
    print('* 写入压缩包 ...')
   # Pack
    return compress('./build', output_name=filename)


if __name__ == '__main__':
    datadict = manifest_data()
    cmdtable = PrettyTable(['命令', '解释'])
    cmdtable.add_row(['build', '现在开始构建'])
    cmdtable.add_row(['info', '显示组件包状态'])
    cmdtable.add_row(['enable <filename>', '启用文件名为参数 filename 的组件包'])
    cmdtable.add_row(['disable <filename>', '禁用文件名为参数 filename 的组件包'])
    print('\n'*20)
    while True:
        print('+', '-'*57, '+', sep='')
        print('|', '欢迎使用 Crazy MC 构建程序'.center(49), '|', sep='')
        print('|', 'by SNWCreations, 2021/7'.center(57), '|', sep='')
        print(cmdtable)
        x = input('* 请输入命令:')
        if x == 'build':
            print('\n'*10)
            sfn = build(datadict, 'build.zip')
            print('* 构建完成，保存到:', sfn)
            shutil.rmtree('build')
            time.sleep(3)
            sys.exit()
        elif x == 'info':
            show_info(datadict)
            time.sleep(5)
        elif not re.match('disable', x) or not re.match('enable', x):
            dobj = re.match('disable', x)
            if not dobj == None:
                n = os.path.abspath('./packs/' + x[8:])
                try:
                    active.remove(n)
                except:
                    pass
                continue
            eobj = re.match('enable', x)
            if not eobj == None:
                n = os.path.abspath('./packs/' + x[7:])
                active.add(n)
        else:
            print('* 无效命令')
